// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.designer.ui.editors;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.dengues.core.IScriptsPluginService;
import org.dengues.core.external.AbstractCompNodeExt;
import org.dengues.core.external.IExternalData;
import org.dengues.core.mapper.IMapperDataTable;
import org.dengues.core.mapper.IMapperExternalData;
import org.dengues.core.process.EConnectionType;
import org.dengues.core.process.ICompConnection;
import org.dengues.designer.ui.editors.actions.GEFCopyAction;
import org.dengues.designer.ui.editors.actions.GEFCutAction;
import org.dengues.designer.ui.editors.actions.GEFDeleteAction;
import org.dengues.designer.ui.editors.actions.GEFPasteAction;
import org.dengues.designer.ui.process.actions.ConnectionCreateAction;
import org.dengues.designer.ui.process.editors.GEFComponentsEditor;
import org.dengues.designer.ui.process.models.CompBlock;
import org.dengues.designer.ui.process.models.CompBlockExit;
import org.dengues.designer.ui.process.models.CompNode;
import org.dengues.designer.ui.process.parts.CompBlockPart;
import org.eclipse.gef.ContextMenuProvider;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gef.ui.actions.ActionRegistry;
import org.eclipse.gef.ui.actions.GEFActionConstants;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.actions.ActionFactory;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf 1 2006-09-29 17:06:40Z qiang.zhang $
 * 
 */
public class GEFEditorContextMenuProvider extends ContextMenuProvider {

    private final ActionRegistry actionRegistry;

    private final IWorkbenchPart part;

    private static final String GROUP_CONNECTIONS = "ConnectionsGroup"; //$NON-NLS-1$

    /**
     * Qiang.Zhang.Adolf@gmail.com GEFEditorContextMenuProvider constructor comment.
     * 
     * @param part
     * @param viewer
     * @param registry
     */
    public GEFEditorContextMenuProvider(IWorkbenchPart part, EditPartViewer viewer, ActionRegistry registry) {
        super(viewer);
        if (registry == null) {
            throw new IllegalArgumentException();
        }
        actionRegistry = registry;
        this.part = part;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.gef.ContextMenuProvider#buildContextMenu(org.eclipse.jface.action.IMenuManager)
     */
    @Override
    public void buildContextMenu(IMenuManager menu) {
        if (part != null) {
            IAction action = null;
            // for the block enter connection
            if (part instanceof GEFComponentsEditor) {
                EditPart focusEditPart = getViewer().getFocusEditPart();
                if (focusEditPart instanceof CompBlockPart) {
                    CompBlockPart blockPart = (CompBlockPart) focusEditPart;
                    if (blockPart.getModel() instanceof CompBlockExit) {
                        CompBlockExit blockExit = (CompBlockExit) blockPart.getModel();
                        if (blockExit.isEnter()) {
                            action = new ConnectionCreateAction(this.part, EConnectionType.MAIN);
                        }
                    } else if (blockPart.getModel() instanceof CompBlock) {
                        CompBlock block = (CompBlock) blockPart.getModel();
                        List<String> enames = block.getExitNames();
                        for (String string : enames) {
                            action = new ConnectionCreateAction(this.part, EConnectionType.MAIN, string);
                        }
                    }
                } else {
                    addNodeMenu(menu, focusEditPart);
                }
            }
            menu.add(new Separator(GEFActionConstants.GROUP_UNDO));
            menu.add(new Separator(GEFActionConstants.GROUP_COPY));
            menu.add(new Separator(GEFActionConstants.GROUP_EDIT));

            menu.appendToGroup(GEFActionConstants.GROUP_UNDO, getAction(ActionFactory.UNDO.getId()));
            menu.appendToGroup(GEFActionConstants.GROUP_UNDO, getAction(ActionFactory.REDO.getId()));

            action = getAction(ActionFactory.COPY.getId());
            ((GEFCopyAction) action).update();
            menu.appendToGroup(GEFActionConstants.GROUP_COPY, action);

            action = getAction(ActionFactory.CUT.getId());
            if (action != null) {
                ((GEFCutAction) action).update();
                menu.appendToGroup(GEFActionConstants.GROUP_COPY, action);
            }

            action = getAction(ActionFactory.PASTE.getId());
            ((GEFPasteAction) action).update();
            menu.appendToGroup(GEFActionConstants.GROUP_COPY, action);

            action = getAction(ActionFactory.DELETE.getId());
            ((GEFDeleteAction) action).update();
            menu.appendToGroup(GEFActionConstants.GROUP_EDIT, action);
            menu.appendToGroup(GEFActionConstants.GROUP_EDIT, getAction(ActionFactory.SELECT_ALL.getId()));
        }

    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "addNodeMenu".
     * 
     * @param menu
     * @param focusEditPart
     */
    private void addNodeMenu(IMenuManager menu, EditPart focusEditPart) {
        EConnectionType[] values = EConnectionType.values();
        IAction action;
        Map<String, List<IAction>> map = new HashMap<String, List<IAction>>();
        for (EConnectionType cty : values) {
            action = getAction(ConnectionCreateAction.ID + cty.toString());
            if (action != null) {
                ConnectionCreateAction connAction = ((ConnectionCreateAction) action);
                connAction.update();
                if (connAction.isEnabled()) {
                    addConnectionAction(map, connAction, cty, focusEditPart);
                }
            }
        }
        for (String itemName : map.keySet()) {
            List<IAction> list = map.get(itemName);
            if (!list.isEmpty()) {
                menu.add(new Separator(GROUP_CONNECTIONS));
                MenuManager subMenu = new MenuManager(itemName);
                menu.appendToGroup(GROUP_CONNECTIONS, subMenu);
                for (IAction action2 : list) {
                    subMenu.add(action2);
                }
            }
        }
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "addConnectionAction".
     * 
     * @param map
     * @param connAction
     * @param cty
     * @param focusEditPart
     */
    private void addConnectionAction(Map<String, List<IAction>> map, ConnectionCreateAction connAction, EConnectionType cty,
            EditPart focusEditPart) {
        List<IAction> list = map.get(cty.getItemName());
        if (list == null) {
            list = new ArrayList<IAction>();
        }
        CompNode compNode = (CompNode) focusEditPart.getModel();
        if (compNode.isExternalNode() && EConnectionType.MAIN.equals(cty)) {
            AbstractCompNodeExt eNode = compNode.getExternalNode(false);
            IExternalData eData = eNode.getExternalData();
            if (eData != null) {
                List<ICompConnection> outgoingConnections = compNode.getOutgoingConnections();
                Set<String> set = new HashSet<String>();
                for (ICompConnection compConnection : outgoingConnections) {
                    set.add(compConnection.getName());
                }
                if (eData instanceof IMapperExternalData) {
                    IMapperExternalData data = (IMapperExternalData) eData;
                    List<IMapperDataTable> tables = data.getTables();
                    if (tables != null) {
                        for (IMapperDataTable mDataTable : tables) {
                            if (IScriptsPluginService.MATATPYE_OUTPUT.equals(mDataTable.getMetaType())) {
                                String name = mDataTable.getName();
                                if (!contains(set, name)) {
                                    ConnectionCreateAction action = new ConnectionCreateAction(this.part, cty, cty
                                            .getDisplayName()
                                            + "(" + name + ")");
                                    action.setSelection(connAction.getSelection());
                                    action.setUnName(name);
                                    list.add(action);
                                }
                            }
                        }
                    }
                }
            }
        } else {
            list.add(connAction);
        }
        map.put(cty.getItemName(), list);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "contains".
     * 
     * @param set
     * @param name
     * @return
     */
    private boolean contains(Set<String> set, String name) {
        for (String string : set) {
            if (string.contains(name)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getAction".
     * 
     * @param actionId
     * @return
     */
    private IAction getAction(final String actionId) {
        return actionRegistry.getAction(actionId);
    }

}
